
package com.kugou.game.sdk.ui.activity;

import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.animation.ValueAnimator.AnimatorUpdateListener;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.kugou.game.sdk.api.common.ActivityOrientation;
import com.kugou.game.sdk.api.common.User;
import com.kugou.game.sdk.base.BaseCommonTitleFragmentActivity;
import com.kugou.game.sdk.core.FolderManager;
import com.kugou.game.sdk.core.PayManager;
import com.kugou.game.sdk.core.SDKControler;
import com.kugou.game.sdk.core.UserManager;
import com.kugou.game.sdk.core.VipManager;
import com.kugou.game.sdk.entity.AccountSecurityInfo;
import com.kugou.game.sdk.interfaces.OnQueryYoubiNumListener;
import com.kugou.game.sdk.interfaces.onAccountSecurityInfoListener;
import com.kugou.game.sdk.persistence.preference.PrefUtil;
import com.kugou.game.sdk.ui.fragment.AccountSecurityFragment;
import com.kugou.game.sdk.ui.widget.GameFitGridRelativeLayout;
import com.kugou.game.sdk.ui.widget.LoadingView;
import com.kugou.game.sdk.utils.AppUtil;
import com.kugou.game.sdk.utils.AsyncImageLoader;
import com.kugou.game.sdk.utils.AsyncImageLoader.ImageCallback;
import com.kugou.game.sdk.utils.Rx;
import com.kugou.game.sdk.utils.ToastUtil;

/**
 * 描述:游币充值成功界面
 *
 * @author wcj
 * @since 2015年8月25日 下午4:02:16
 */
public class KubiRechargeSuccessActivity extends BaseCommonTitleFragmentActivity {

    private static final int MSG_BACK_SET_PAY_PASSWD = 10000;

    private static final int MSG_UI_SET_PAY_PASSWD_FAILED = 10001;

    private static final int MSG_UI_SET_PAY_PASSWD_SUCCESS = 10002;

    private static final int MSG_UI_SHOW_LOADING_VIEW = 10003;

    private static final int MSG_UI_HIDE_LOADING_VIEW = 10004;

    private static final int MSG_BACK_REQUEST_IS_SET_PAY_PASSWD = 10005;

    private static final int MSG_QUERY_YOUBI_NUM = 10006;

    private static final int MSG_QUERY_YOUBI_NUM_SUCCESS = 10007;

    private static final int MSG_QUERY_YOUBI_NUM_FAILED = 10008;

    private final int MSG_UI_UPDATE_COUNT_DOWN_TV = 10009;

    private float mRechargeValue;

    private Button mConfirmBtn;

    private EditText mLoginPasswdEditText, mPayPasswdEditText;

    private TextView mSuccessResultTV, mYoubiNumRemainTV, mGSCountDown;

    private LoadingView mLoadingView;

    private LinearLayout mSetPayPasswdLayout, mSetPayPasswdSuccessLayout,
            mRechargeSuccessInfoLayout, mSavetyInfolayout, mRechargeSuccessLayout;

    // 安全提示中各种安全措施图标
    private ImageView mPhoneIcon, mEmailIcon, mProblemIcon, mIdCardIcon, mGSInfoImage;

    // GS图片布局
    private GameFitGridRelativeLayout mGSLayout;

    TextView mSaveText;

    private User user;

    private int second = 3;// 倒计时秒数

    private boolean isShow = true;// GS图片显示标识

    private ScrollView mRechargeScrollView;

    public static Intent createIntent(Context context, float rechargeValue) {
        Intent intent = new Intent();
        intent.setClass(context, KubiRechargeSuccessActivity.class);
        intent.putExtra("rechargeValue", rechargeValue);
        return intent;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mRechargeValue = getIntent().getFloatExtra("rechargeValue", 0);

        int layoutId = 0;
        if (SDKControler.getActivityOrientation() == ActivityOrientation.LANDSCAPE) {
            layoutId = Rx.layout.kg_activity_kubi_recharge_success_land;
        } else {
            layoutId = Rx.layout.kg_activity_kubi_recharge_success;
        }
        setContentView(layoutId);
        user = UserManager.getInstance().getCurrentUserInternal();
        initViews();

        sendEmptyBackgroundMessage(MSG_QUERY_YOUBI_NUM);
        sendEmptyUiMessageDelayed(MSG_UI_UPDATE_COUNT_DOWN_TV, 1000);
    }

    int gsheight;

    private void initViews() {
        mRechargeScrollView = (ScrollView) findViewById(Rx.id.kg_recharge_success_scroll);
        final int isSetPasswd = UserManager.getInstance().getCurrentUserInternal().getPayPsd();
        if (isSetPasswd == AccountSecurityInfo.UNKOWN_SET_PAY_PASSWD) {
            sendEmptyBackgroundMessage(MSG_BACK_REQUEST_IS_SET_PAY_PASSWD);
        }

        setCommonTitle("充值成功");

        mLoadingView = (LoadingView) findViewById(Rx.id.kg_loadingView);

        // 整个界面
        mRechargeSuccessLayout = (LinearLayout) findViewById(Rx.id.kg_layout_recharge_success);

        // GS布局
        mGSLayout = (GameFitGridRelativeLayout) findViewById(Rx.id.kg_rl_gs_image);

        if (SDKControler.getActivityOrientation() == ActivityOrientation.LANDSCAPE) {
            mGSLayout.setmScale(5.56f);
        } else {
            mGSLayout.setmScale(2.25f);
        }

        mGSCountDown = (TextView) findViewById(Rx.id.kg_tv_count_second);

        mGSInfoImage = (ImageView) findViewById(Rx.id.kg_iv_gs_image);

        // 充值成功，设置支付密码layout
        mSetPayPasswdLayout = (LinearLayout) findViewById(Rx.id.kg_ll_set_pay_passwd);

        // 设置支付密码成功，显示安全评分layout
        mSetPayPasswdSuccessLayout = (LinearLayout) findViewById(Rx.id.kg_ll_set_passwd_success);

        // 充值成功信息，充多少，余额多少
        mRechargeSuccessInfoLayout = (LinearLayout) findViewById(Rx.id.kg_ll_recharge_success_info);

        mSuccessResultTV = (TextView) findViewById(Rx.id.kg_tv_result);
        TextView successAccountTV = (TextView) findViewById(Rx.id.kg_tv_account);
        successAccountTV.setText("当前账号：" + UserManager.getInstance().getCurrentUserName());
        mYoubiNumRemainTV = (TextView) findViewById(Rx.id.kg_tv_remain);

        mSuccessResultTV.setText("恭喜主人，成功充值" + mRechargeValue + "游币");

        mYoubiNumRemainTV.setText("游币余额："
                + (UserManager.getInstance().getCurrentUserInternal().getKubiNum()) + "游币");

        mConfirmBtn = (Button) findViewById(Rx.id.kg_btn_sure);
        mConfirmBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                hideSoftInput(mContext);
                if (isSetPasswd == AccountSecurityInfo.UN_SET_PAY_PASSWD
                        && UserManager.getInstance().getCurrentUserInternal().isSetKugouPsd()) {
                    sendEmptyBackgroundMessage(MSG_BACK_SET_PAY_PASSWD);
                } else {
                    finish();
                }
            }
        });

        mRechargeScrollView.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int action = event.getAction();
                switch (action) {
                    case MotionEvent.ACTION_UP:
                        int y = mRechargeScrollView.getScrollY();
                        if (y >= gsheight) {
                            isShow = false;
                        } else {
                            mGSCountDown.setVisibility(View.GONE);
                            isShow = true;
                        }
                        break;
                }
                return false;
            }
        });

        // GS相关
        showGSIcon();
        mGSLayout.setVisibility(View.VISIBLE);
        mGSLayout.setFocusable(true);
        mGSLayout.setFocusableInTouchMode(true);
        mGSLayout.requestFocus();
        this.setOnShowGSImageListener(new onShowGSImageListener() {

            @Override
            public void onShow() {
                if (isShow) {
                    hideGS();
                } else {
                    showGS();
                }
            }
        });
        ViewTreeObserver contentObserver = mGSLayout.getViewTreeObserver();
        contentObserver.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if (mGSLayout == null) {
                    return;
                }
                mGSLayout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                gsheight = mGSLayout.getHeight();
            }
        });

        mGSInfoImage.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                String gsQq = VipManager.getInstance().getVipInfo().getGsQQ();
                if (!TextUtils.isEmpty(gsQq)) {
                    ClipboardManager cmb = (ClipboardManager) mContext
                            .getSystemService(Context.CLIPBOARD_SERVICE);
                    cmb.setText(gsQq);
                    ToastUtil.showMsg("QQ群号已复制");
                } else {
                    ToastUtil.showMsg("复制失败");
                }
            }
        });

        String imageUrl = VipManager.getInstance().getGsImage();
        if (!TextUtils.isEmpty(imageUrl)) {
            String savePath = FolderManager.IMAGE_CACHE_FOLDER
                    + AppUtil.getFileNameFromUrl(imageUrl);
            String key = imageUrl;
            Bitmap bitmap = new AsyncImageLoader().loadImage(mContext, key, imageUrl, savePath,
                    new ImageCallback() {

                        @Override
                        public void imageLoaded(Bitmap bitmap, String key) {
                            if (bitmap != null) {
                                mGSInfoImage.setImageBitmap(bitmap);
                            }
                        }
                    });
            if (bitmap != null) {
                mGSInfoImage.setImageBitmap(bitmap);
            }
        }

        mLoginPasswdEditText = (EditText) findViewById(Rx.id.kg_et_input_login_pwd);

        mPayPasswdEditText = (EditText) findViewById(Rx.id.kg_et_input_pay_pwd);

        // 没有设置支付密码 并且 不是第三方登录没有登录密码的情况
        if (isSetPasswd == AccountSecurityInfo.UN_SET_PAY_PASSWD
                && UserManager.getInstance().getCurrentUserInternal().isSetKugouPsd()) {
            mConfirmBtn.setText("确认");
            mSetPayPasswdLayout.setVisibility(View.VISIBLE);
        }

        mSavetyInfolayout = (LinearLayout) findViewById(Rx.id.kg_ll_set_save_info);
        mProblemIcon = (ImageView) findViewById(Rx.id.kg_iv_problem_icon);
        mEmailIcon = (ImageView) findViewById(Rx.id.kg_iv_email_icon);
        mPhoneIcon = (ImageView) findViewById(Rx.id.kg_iv_phone_icon);
        mIdCardIcon = (ImageView) findViewById(Rx.id.kg_iv_idcard_icon);
        mSaveText = (TextView) findViewById(Rx.id.kg_tv_safety_score);

        if (isSetPasswd == AccountSecurityInfo.HAD_SET_PAY_PASSWD
                && UserManager.getInstance().getCurrentUserInternal().getSecurityScore() < 100
                && PrefUtil.getPaySecurityTipNeedShow(KubiRechargeSuccessActivity.this,
                        user.getOpenId()) && PayManager.getPaySecurityTipNeedShow(user.getOpenId())) {
            mConfirmBtn.setVisibility(View.GONE);
            mSetPayPasswdSuccessLayout.setVisibility(View.VISIBLE);
            showSavetyInfoViews(UserManager.getInstance().getCurrentUserInternal());
        }
    }

    private void showSavetyInfoViews(final AccountSecurityInfo info) {

        final CheckBox isShowSavetyInfo = (CheckBox) findViewById(Rx.id.kg_iv_checkbox);

        Button confirmBtn = (Button) findViewById(Rx.id.kg_btn_confirm);
        confirmBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                if (isShowSavetyInfo.isChecked()) {
                    PrefUtil.setPaySecurityTipNeedShow(KubiRechargeSuccessActivity.this,
                            user.getOpenId(), false);
                    PayManager.setPaySecurityTipNeedShow(user.getOpenId());
                }

                if (info.getSecurityScore() < 100
                        && PrefUtil.getPaySecurityTipNeedShow(KubiRechargeSuccessActivity.this,
                                user.getOpenId())
                        && PayManager.getPaySecurityTipNeedShow(user.getOpenId())) {
                    // 跳转到安全设置界面
                    startActivity(CommonSdkActivity.creatIntent(KubiRechargeSuccessActivity.this,
                            AccountSecurityFragment.class.getName(), Rx.string.kg_accout_security));

                }
                finish();
            }
        });

        if (info.getSecurityScore() < 100
                && PrefUtil.getPaySecurityTipNeedShow(KubiRechargeSuccessActivity.this,
                        user.getOpenId())
                && PayManager.getPaySecurityTipNeedShow(UserManager.getInstance()
                        .getCurrentUserInternal().getOpenId())) {
            mSavetyInfolayout.setVisibility(View.VISIBLE);
            mSaveText.setText("您当前账号安全评分：" + info.getSecurityScore() + "分");
            confirmBtn.setText("立即设置");

            if (info.getSecurityQuestionId() >= 0 && info.getSecurityQuestionId() != 255) {
                mProblemIcon.setImageResource(Rx.drawable.kg_security_question_set);
            }

            if (!TextUtils.isEmpty(info.getSecurityEmail())) {
                mEmailIcon.setImageResource(Rx.drawable.kg_security_email_binded);
            }

            if (!TextUtils.isEmpty(UserManager.getInstance().getCurrentUserInternal()
                    .getBindPhoneNum())) {
                mPhoneIcon.setImageResource(Rx.drawable.kg_security_phone_binded);
            }

            if (info.isSetIdentity()) {
                mIdCardIcon.setImageResource(Rx.drawable.kg_security_identity_binded);
            }
        } else {
            confirmBtn.setText("确认");
        }
    }

    @Override
    public void handleUiMessage(Message msg) {
        super.handleUiMessage(msg);
        switch (msg.what) {
            case MSG_UI_SET_PAY_PASSWD_FAILED:
                sendEmptyUiMessage(MSG_UI_HIDE_LOADING_VIEW);
                showToast((String) msg.obj);
                mRechargeScrollView.smoothScrollBy(0, 20);
                break;

            case MSG_UI_SET_PAY_PASSWD_SUCCESS:
                sendEmptyUiMessage(MSG_UI_HIDE_LOADING_VIEW);
                mRechargeScrollView.smoothScrollBy(0, 20);
                if (((AccountSecurityInfo) msg.obj).getSecurityScore() < 100) {
                    mRechargeSuccessInfoLayout.setVisibility(View.GONE);
                    mSetPayPasswdSuccessLayout.setVisibility(View.VISIBLE);
                    mSuccessResultTV.setText("支付密码设置成功");
                    showSavetyInfoViews((AccountSecurityInfo) msg.obj);
                } else {
                    finish();
                }
                break;

            case MSG_UI_SHOW_LOADING_VIEW:
                mRechargeScrollView.setVisibility(View.GONE);
                mLoadingView.setVisibility(View.VISIBLE);
                break;

            case MSG_UI_HIDE_LOADING_VIEW:
                mRechargeScrollView.setVisibility(View.VISIBLE);
                mLoadingView.setVisibility(View.GONE);
                break;

            case MSG_QUERY_YOUBI_NUM_SUCCESS:
                sendEmptyUiMessage(MSG_UI_HIDE_LOADING_VIEW);
                mYoubiNumRemainTV.setText("游币余额："
                        + (UserManager.getInstance().getCurrentUserInternal().getKubiNum()) + "游币");
                break;

            case MSG_QUERY_YOUBI_NUM_FAILED:
                sendEmptyBackgroundMessageDelayed(MSG_QUERY_YOUBI_NUM, 500);
                break;

            case MSG_UI_UPDATE_COUNT_DOWN_TV:
                if (isShow) {
                    // 更新倒计时文本
                    mGSCountDown.setVisibility(View.VISIBLE);
                    mGSCountDown.setText(second + "秒");
                    second--;
                    if (second >= 0) {
                        sendEmptyUiMessageDelayed(MSG_UI_UPDATE_COUNT_DOWN_TV, 1000);
                    } else {
                        hideGS();
                    }
                }
                break;

            default:
                break;
        }
    }

    @Override
    public void handleBackgroundMessage(Message msg) {
        super.handleBackgroundMessage(msg);

        switch (msg.what) {
            case MSG_BACK_SET_PAY_PASSWD:
                if (checkPasswd()) {
                    sendEmptyUiMessage(MSG_UI_SHOW_LOADING_VIEW);
                    setPayPasswd();
                }
                break;

            case MSG_BACK_REQUEST_IS_SET_PAY_PASSWD:
                UserManager.getInstance().requestAccountSecurityInfo(
                        new onAccountSecurityInfoListener() {

                            @Override
                            public void onSuccess(AccountSecurityInfo info) {
                            }

                            @Override
                            public void onFaile(String errorMsg) {
                            }
                        });
                break;

            case MSG_QUERY_YOUBI_NUM:
                sendEmptyUiMessage(MSG_UI_SHOW_LOADING_VIEW);
                UserManager.getInstance().queryYoubiNum(new OnQueryYoubiNumListener() {

                    @Override
                    public void onSuccess(int youbiNum) {
                        UserManager.getInstance().getCurrentUserInternal().setKubiNum(youbiNum);
                        sendEmptyUiMessage(MSG_QUERY_YOUBI_NUM_SUCCESS);
                    }

                    @Override
                    public void onFailed(String errorMsg) {
                        sendEmptyUiMessage(MSG_QUERY_YOUBI_NUM_FAILED);
                    }
                });
                break;

            default:
                break;
        }
    }

    private boolean checkPasswd() {
        if (TextUtils.isEmpty(mLoginPasswdEditText.getText())) {
            showToast("登录密码不能为空");
            return false;
        }

        if (TextUtils.isEmpty(mPayPasswdEditText.getText())
                || mPayPasswdEditText.getText().toString().length() < 6) {
            showToast("支付密码必须为6位数字");
            return false;
        }
        return true;
    }

    private void setPayPasswd() {
        String userName = UserManager.getInstance().getCurrentUserName();

        UserManager.getInstance().setPayPsd(userName, mLoginPasswdEditText.getText().toString(),
                mPayPasswdEditText.getText().toString(), new onAccountSecurityInfoListener() {

                    @Override
                    public void onSuccess(AccountSecurityInfo info) {
                        Message msg = Message.obtain();
                        msg.what = MSG_UI_SET_PAY_PASSWD_SUCCESS;
                        msg.obj = info;
                        sendUiMessage(msg);
                    }

                    @Override
                    public void onFaile(String errorMsg) {
                        Message msg = Message.obtain();
                        msg.what = MSG_UI_SET_PAY_PASSWD_FAILED;
                        msg.obj = errorMsg;
                        sendUiMessage(msg);
                    }
                });
    }

    private void hideGS() {
        mGSCountDown.setVisibility(View.GONE);// 隐藏倒计时文本
        mRechargeScrollView.smoothScrollBy(0, gsheight);
        isShow = false;
    }

    private void showGS() {
        isShow = true;
        mRechargeScrollView.smoothScrollTo(0, 0);
    }

    public void hideGSLayout() {
        isShow = false;
        int height = mGSLayout.getHeight();// GS图片布局高度
        mGSCountDown.setVisibility(View.GONE);
        ObjectAnimator hideGSLayout = ObjectAnimator.ofFloat(mRechargeSuccessLayout, "y", 0,
                -height);
        hideGSLayout.setDuration(300).start();
        hideGSLayout.addUpdateListener(new AnimatorUpdateListener() {

            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                // TODO Auto-generated method stub
                mRechargeSuccessLayout.setY((Float) animation.getAnimatedValue());
            }
        });
    }

    public void showGSLayout() {
        isShow = true;
        int height = mGSLayout.getHeight();
        ObjectAnimator hideGSLayout = ObjectAnimator.ofFloat(mRechargeSuccessLayout, "y", -height,
                0);
        hideGSLayout.setDuration(300).start();
        hideGSLayout.addUpdateListener(new AnimatorUpdateListener() {

            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                // TODO Auto-generated method stub
                mRechargeSuccessLayout.setY((Float) animation.getAnimatedValue());
            }
        });
    }

}
